import "./style.css";

const btn = document.getElementById("theme-toggle");
const darkIcon = document.getElementById("theme-toggle-dark-icon");
const lightIcon = document.getElementById("theme-toggle-light-icon");

// https://www.freecodecamp.org/news/how-to-build-a-dark-mode-switcher-with-tailwind-css-and-flowbite
if (
  localStorage.getItem("color-theme") === "dark" ||
  (!("color-theme" in localStorage) &&
    window.matchMedia("(prefers-color-scheme: dark)").matches)
) {
  document.documentElement.classList.add("dark");
  lightIcon.classList.remove("hidden");
} else {
  document.documentElement.classList.remove("dark");
  darkIcon.classList.remove("hidden");
}

btn.addEventListener("click", () => {
  darkIcon.classList.toggle("hidden");
  lightIcon.classList.toggle("hidden");
  const setLightMode = () => {
    localStorage.setItem("color-theme", "light");
    document.documentElement.classList.remove("dark");
  };
  const setDarkMode = () => {
    localStorage.setItem("color-theme", "dark");
    document.documentElement.classList.add("dark");
  };
  const saveMode = localStorage.getItem("color-theme");
  if (saveMode) {
    if (saveMode === "dark") {
      setLightMode();
    } else {
      setDarkMode();
    }
    return;
  }
  if (document.documentElement.classList.contains("dark")) {
    setLightMode();
    return;
  }
  setDarkMode();
});
